package com.example.texting;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;
import android.widget.Toast;

public class SMSreceiver extends BroadcastReceiver {
	
	// log tags for debugging
    private static final String TAG = "SMSBroadcastReceiver";
    
	@Override
	public void onReceive(Context context, Intent intent) {
		Log.i(TAG, "Intent recieved: " + intent.getAction());
		
		// pull data from intent
		Bundle bundle = intent.getExtras();
		Object[] messages = (Object[]) intent.getSerializableExtra("pdus");
		
		
		if (bundle != null) {
			
			byte[][] pduObjs = new byte[messages.length][];

			for (int i = 0; i < messages.length; i++) {
				pduObjs[i] = (byte[]) messages[i];
			}
			
			// parse pdus into SmsMessage type for getting message and sender
			byte[][] pdus = new byte[pduObjs.length][];
			int pduCount = pdus.length;
			SmsMessage[] msgs = new SmsMessage[pduCount];

			for (int i = 0; i < pduCount; i++) {
				pdus[i] = pduObjs[i];
				msgs[i] = SmsMessage.createFromPdu(pdus[i]);
			} 
			
            Toast.makeText( context, msgs[0].getMessageBody(), Toast.LENGTH_SHORT).show();
            
            Intent i = new Intent();
            i.setClass(context, TextEncryptor.class);
            i.setAction(TextEncryptor.class.getName());
            i.putExtra("msg", msgs[0].getMessageBody());
            i.putExtra("phnum", msgs[0].getOriginatingAddress());
            i.setFlags(
            		Intent.FLAG_ACTIVITY_NEW_TASK
            		| Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
            Log.i(TAG, "About to Start activity i: " + i.getAction());
            context.startActivity(i);

		}
		else{
			// write to log if no text recieved
			Log.i(TAG, "Receiver Bundle Empty: " + intent.getAction());
		}
	}	
}